package com.lcd.ssm.web.interceptor;

import com.lcd.ssm.domain.Employee;
import com.lcd.ssm.util.PermissionUtil;
import com.lcd.ssm.util.UserContext;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * lcd  2020/4/27
 * Description:
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        UserContext.setRequest(httpServletRequest);
        Employee employee = (Employee) httpServletRequest.getSession().getAttribute(UserContext.USER_SESSION);
        if (employee == null) {
            httpServletResponse.sendRedirect("/login.jsp");
            return false;
        }else{
            //管理员放行
            if (employee.getAdmin()) {
                return true;
            }
            //判断是否静态资源
            if(handler instanceof HandlerMethod){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                String beanName = handlerMethod.getBean().getClass().getName();
                String methodName = handlerMethod.getMethod().getName();
                //当前请求的权限表达式
                String rbacStr = beanName + ":" + methodName;
                boolean flag= PermissionUtil.judge(rbacStr);
                if (flag) {
                    return true;
                }else {
                    //判断ajax还是页面
                    if (handlerMethod.getMethod().isAnnotationPresent(ResponseBody.class)) {
                        httpServletResponse.sendRedirect("/nopermission.json");
                    }else {
                        httpServletResponse.sendRedirect("/nopermission.jsp");
                    }
                    return false;
                }
            }else {
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
